package ru.paswd.marketprice.utils

import android.content.Context
import android.graphics.*
import android.graphics.drawable.Drawable
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.DrawableCompat


object DrawableUtils {
    fun getBitmapFromVectorDrawable(context: Context, drawableId: Int): Bitmap {
        val drawable = ContextCompat.getDrawable(context, drawableId)
        val bitmap = Bitmap.createBitmap(drawable!!.intrinsicWidth,
                drawable.intrinsicHeight, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bitmap)
        drawable.setBounds(0, 0, canvas.width, canvas.height)
        drawable.draw(canvas)
        return bitmap
    }

    fun tintImage(bitmap: Bitmap, color: Int): Bitmap {
        val paint = Paint()
        paint.colorFilter = PorterDuffColorFilter(color, PorterDuff.Mode.SRC_IN)
        val bitmapResult = Bitmap.createBitmap(bitmap.width, bitmap.height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bitmapResult)
        canvas.drawBitmap(bitmap, 0f, 0f, paint)
        return bitmapResult
    }

    fun tintImage(context: Context, drawableId: Int, color: Int): Drawable {

        var drawable = ContextCompat.getDrawable(
                context, drawableId)!!.mutate()

        drawable = DrawableCompat.wrap(drawable)
        DrawableCompat.setTint(drawable, color)

        return drawable
    }

    fun mergeBitmaps(back: Bitmap, front: Bitmap): Bitmap? {
        val result = Bitmap.createBitmap(back.width, back.height, back.config)
        val canvas = Canvas(result)
        val widthBack = back.width
        val widthFront = front.width
        val move = ((widthBack - widthFront) / 2).toFloat()
        canvas.drawBitmap(back, 0f, 0f, null)
        canvas.drawBitmap(front, move, move, null)
        return result
    }
}